package com.derbysoft.ota.application.util;

import java.math.BigDecimal;
import java.math.BigInteger;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.beanutils.converters.BigIntegerConverter;

import com.google.common.base.Throwables;
import com.googlecode.functionalcollections.Block;
import com.googlecode.functionalcollections.FunctionalIterable;

public abstract class Beans {

	static {
		registerConverters();
	}

	private static void registerConverters() {
		ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class);
		ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);
	}
	
	public static <T> T copyProperties(final Object src, final T target, FunctionalIterable<String> fieldNames) {
		fieldNames.each(new Block<String>() {
			public void apply(String fieldName) {
				try {
					BeanUtils.setProperty(target, fieldName, BeanUtils.getProperty(src, fieldName));
				} catch (Exception e) {
					throw Throwables.propagate(e);
				} 
			}
		});
		return target;
	}

	public static Object setProperty(Object bean, String name, Object value) {
		try {
			BeanUtils.setProperty(bean, name, value);
		} catch (Exception e) {
			throw Throwables.propagate(e);
		} 
		return bean;
	}

	public static Object getProperty(Object bean, String name) {
		try {
			return BeanUtils.getProperty(bean, name);
		} catch (Exception e) {
			throw Throwables.propagate(e);
		}
	}
	
}
